import Router from 'koa-router'
import redis from '../../utils/redis.js'

const CONN_PREFIX = 'webrtc:conn:'
const ROOM_PREFIX = 'webrtc:room:'

const router = new Router({ prefix: '/connections' })

// 在线连接列表
router.get('/', async (ctx) => {
  const keys = await redis.keys(CONN_PREFIX + '*')
  const list = []
  for (const key of keys) {
    const connInfo = await redis.get(key)
    if (!connInfo) continue
    try {
      const parsed = JSON.parse(connInfo)
      list.push({
        connId: key.replace(CONN_PREFIX, ''),
        roomId: parsed.roomId,
        uid: parsed.uid
      })
    } catch (e) {}
  }
  ctx.body = { connections: list }
})

// 踢下线
router.post('/:connId/kick', async (ctx) => {
  const { connId } = ctx.params

  const payload = {
    cmd: 'cmd_admin_kick',
    type: 'kick'
  }
  await redis.publish('webrtc:broadcast', JSON.stringify({ connId, payload }))
  ctx.body = { success: true }
})

export default router


